package com.ruoyi.system.service.impl;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.CSVCatalystsQualityEntry;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysCatalystsQualityMapper;
import com.ruoyi.system.domain.SysCatalystsQuality;
import com.ruoyi.system.service.ISysCatalystsQualityService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 催化剂质量检测Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-11
 */
@Service
public class SysCatalystsQualityServiceImpl implements ISysCatalystsQualityService 
{
    @Autowired
    private SysCatalystsQualityMapper sysCatalystsQualityMapper;

    /**
     * 查询催化剂质量检测
     * 
     * @param catalystsQualityId 催化剂质量检测主键
     * @return 催化剂质量检测
     */
    @Override
    public SysCatalystsQuality selectSysCatalystsQualityByCatalystsQualityId(Long catalystsQualityId)
    {
        return sysCatalystsQualityMapper.selectSysCatalystsQualityByCatalystsQualityId(catalystsQualityId);
    }

    /**
     * 查询催化剂质量检测列表
     * 
     * @param sysCatalystsQuality 催化剂质量检测
     * @return 催化剂质量检测
     */
    @Override
    public List<SysCatalystsQuality> selectSysCatalystsQualityList(SysCatalystsQuality sysCatalystsQuality)
    {
        return sysCatalystsQualityMapper.selectSysCatalystsQualityList(sysCatalystsQuality);
    }

    /**
     * 新增催化剂质量检测
     * 
     * @param sysCatalystsQuality 催化剂质量检测
     * @return 结果
     */
    @Override
    public int insertSysCatalystsQuality(SysCatalystsQuality sysCatalystsQuality)
    {
        sysCatalystsQuality.setCreateTime(DateUtils.getNowDate());
        return sysCatalystsQualityMapper.insertSysCatalystsQuality(sysCatalystsQuality);
    }

    /**
     * 修改催化剂质量检测
     * 
     * @param sysCatalystsQuality 催化剂质量检测
     * @return 结果
     */
    @Override
    public int updateSysCatalystsQuality(SysCatalystsQuality sysCatalystsQuality)
    {
        sysCatalystsQuality.setUpdateTime(DateUtils.getNowDate());
        return sysCatalystsQualityMapper.updateSysCatalystsQuality(sysCatalystsQuality);
    }

    /**
     * 批量删除催化剂质量检测
     * 
     * @param catalystsQualityIds 需要删除的催化剂质量检测主键
     * @return 结果
     */
    @Override
    public int deleteSysCatalystsQualityByCatalystsQualityIds(Long[] catalystsQualityIds)
    {
        return sysCatalystsQualityMapper.deleteSysCatalystsQualityByCatalystsQualityIds(catalystsQualityIds);
    }

    /**
     * 删除催化剂质量检测信息
     * 
     * @param catalystsQualityId 催化剂质量检测主键
     * @return 结果
     */
    @Override
    public int deleteSysCatalystsQualityByCatalystsQualityId(Long catalystsQualityId)
    {
        return sysCatalystsQualityMapper.deleteSysCatalystsQualityByCatalystsQualityId(catalystsQualityId);
    }

    /**
     * 校验批次号是否存在
     * @param list
     * @return
     */
    @Override
    public List<String>checkNotExist(List<CSVCatalystsQualityEntry> list){
        return sysCatalystsQualityMapper.checkNotExist(list);
    }

    /**
     * 批量插入
     * @param list
     * @return
     */
    @Override
    @Transactional
    public int insertSysCatalystsQualityList(List<SysCatalystsQuality> list){

        return this.batchInsertSysCatalystsQuality(list);
    }

    @Transactional
    public int batchInsertSysCatalystsQuality(List<SysCatalystsQuality> list){
        int batchSize = 500;
        int batch = list.size() / batchSize;
        int lastSize = list.size() % batchSize;
        for (int i = batchSize; i <= batch * batchSize; i = i + batchSize) {
            List<SysCatalystsQuality> insertList = list.subList(i - batchSize, i);
            sysCatalystsQualityMapper.insertSysCatalystsQualityList(insertList);
        }
        if (lastSize > 0) {
            List<SysCatalystsQuality> lastList = list.subList(batch * batchSize, list.size());
            sysCatalystsQualityMapper.insertSysCatalystsQualityList(lastList);
        }
        return list.size();
    }

    /**
     * 导出数据
     * @param list
     * @param type
     * @return
     */
    @Override
    public Workbook export(List<SysCatalystsQuality> list , String type) {
        // 创建一个Excel工作簿
        Workbook workbook = new XSSFWorkbook(); // 创建XLSX格式的Workbook
        //单体导出
        if (type.equals("0")){
            writeExcel(workbook, "来料检测报告", list);
        }
        //按日期导出到不同Sheet
        else {
            //按批次分组
            Map<String,List<SysCatalystsQuality>> map =  list.stream().collect(Collectors.groupingBy(SysCatalystsQuality::getSimpleCreateDate));
            for (Map.Entry<String, List<SysCatalystsQuality>> entry : map.entrySet()) {
                writeExcel(workbook, entry.getKey(), entry.getValue());
            }

        }
        return workbook;
    }

    private void writeExcel(Workbook workbook, String sheetName, List<SysCatalystsQuality> list){
        Sheet sheet = workbook.createSheet(sheetName);
        //冻结前四行
        sheet.createFreezePane(0, 4, 0, 4);
        //前四行行高分别为25 22.5 22.5 45
        Row row0 = sheet.createRow(0);
        row0.setHeight(getHeight(25.5f));
        Row row1 = sheet.createRow(1);
        row1.setHeight(getHeight(22.5f));
        Row row2 = sheet.createRow(2);
        row2.setHeight(getHeight(22.5f));
        Row row3 = sheet.createRow(3);
        row3.setHeight(getHeight(45));

        XSSFColor titleColor = new XSSFColor(new java.awt.Color(247, 246, 182),new DefaultIndexedColorMap());

        //标题
        String[] titles = new String[]{"编号", "外观", "层数", "重量", "净重\n煅烧减重\n1.2kg", "裁切宽度", "堆叠宽度", "尺寸判\n定", "初步判定", "让步放行",
                "最终判定", "昆昇批次号", "昆昇编\n号", "复测\n重量", "备注"};
        float[] widths = new float[]{119, 141, 101, 98, 96, 90, 94, 72, 99, 99, 99, 99, 72, 52,72};
        //合并第一行
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, titles.length - 2));
        //标题样式
        CellStyle style1 = getCellStyle(workbook,20, titleColor);
        Cell titleCell = row0.createCell(0);
        titleCell.setCellValue("来料检测报告");
        titleCell.setCellStyle(style1);

        //第二行标题
        String[] secondTitle = new String[]{"供应商", "", "批次号", "", "", "", "型号", "", "", "到货日期", "", "检验员", "", ""};
        CellStyle style2 = getCellStyle(workbook,12, titleColor);
        for (int i = 0; i < secondTitle.length; i++){
            Cell cell = row1.createCell(i);
            cell.setCellValue(secondTitle[i]);
            cell.setCellStyle(style2);
        }

        //第三行标题
        String[] thirdTitle = new String[]{"名称", "白载体", "数量", "", "", "", "测试时间", "", "","到货日期", "", "审核", "", ""};
        CellStyle style3 = getCellStyle(workbook,12, titleColor);
        for (int i = 0; i < thirdTitle.length; i++){
            Cell cell = row2.createCell(i);
            cell.setCellValue(thirdTitle[i]);
            cell.setCellStyle(style3);
        }
        //合并批次号
        sheet.addMergedRegion(new CellRangeAddress( 1, 1 ,2, 3));
        sheet.addMergedRegion(new CellRangeAddress( 1, 1 ,4, 5));

        //合并数量
        sheet.addMergedRegion(new CellRangeAddress( 2, 2 ,2, 3));
        sheet.addMergedRegion(new CellRangeAddress( 2, 2 ,4, 5));
        //型号
        sheet.addMergedRegion(new CellRangeAddress( 1, 1 ,7, 8));

        //时间
        sheet.addMergedRegion(new CellRangeAddress( 2, 2 ,7, 8));
        //检验员
        sheet.addMergedRegion(new CellRangeAddress( 1, 1 ,12, 13));
        //审核
        sheet.addMergedRegion(new CellRangeAddress( 2, 2 ,12, 13));

        CellStyle style4 = getCellStyle(workbook,12, titleColor);

        for (int i = 0; i < titles.length; i++){
            style4.setWrapText( true);//自动换行
            sheet.setColumnWidth(i, getWidth(widths[i]));
            row3.createCell(i).setCellValue(new XSSFRichTextString(titles[i]));
            row3.getCell(i).setCellStyle(style4);
        }
        CellStyle contentStyle = getCellStyle(workbook,11, null);
        //内容
        for (int i = 0; i < list.size(); i++){
            SysCatalystsQuality sysCatalystsQuality = list.get(i);
            List<String> contentList = sysCatalystsQuality.toContentList();
            Row row = sheet.createRow(i + 4);
            row.setHeight(getHeight(22.0f));
            for (int j = 0; j < contentList.size(); j++){
                //层数
                if (j == 2) {
                    int value = Integer.parseInt(contentList.get(j));
                    row.createCell(j).setCellValue(value);
                }else if (j>2 && j<7){
                    String value = contentList.get(j);
                    if (StringUtils.isNotEmpty(value)){
                        row.createCell(j).setCellValue(Double.parseDouble(value));
                    }else {
                        row.createCell(j).setCellValue(0);
                    }
                }else {
                    row.createCell(j).setCellValue(contentList.get(j));
                }
                row.getCell(j).setCellStyle(contentStyle);
            }
        }

        String[][] footContent = new String[][]{
                new String[]{"规格情况", "最大值", "", "", "", "", "", "接收情况", "", "初步判定不合格数量", "", "0", "", ""},
                new String[]{"", "最小值", "", "", "", "", "", "", "", "让步放行数量", "", "0", "", ""},
                new String[]{"", "平均值",  "", "", "", "", "", "", "", "最终判定不合格数量", "", "0", "", ""},
                new String[]{"", "中位数",  "", "", "", "", "", "", "", "尺寸异常数", "", "0", "", ""},
                new String[]{"备注", "", "", "", "", "", "", "", "", "", "", "", "", ""}
        };
        //公式列表
        String[] formulas = new String[]{
                "MAX",
                "MIN",
                "AVERAGE",
                "MEDIAN"
        };


        //统计区域
        CellStyle footStyle = getCellStyle(workbook,16, null);
        CellStyle footContentStyle = getCellStyle(workbook,12, null);
        for (int i = 0; i < footContent.length; i++) {
            Row footerRow = sheet.createRow(list.size() + 4 + i);
            if (i == 4){
                footerRow.setHeight(getHeight(28.0f));
            } else {
                footerRow.setHeight(getHeight(54.0f));
            }
            for (int j = 0; j < footContent[i].length; j++){
                footerRow.createCell(j).setCellValue(footContent[i][j]);
                if (j == 0 || j == 7){
                    footerRow.getCell(j).setCellStyle(footStyle);
                }else {
                    footerRow.getCell(j).setCellStyle(footContentStyle);
                }
            }
            sheet.addMergedRegion(new CellRangeAddress(list.size() + 4 + i, list.size() + 4 + i, 9, 10));
            sheet.addMergedRegion(new CellRangeAddress(list.size() + 4 + i, list.size() + 4 + i, 11, 13));
            //增加公式
            if (i < 4) {
                //层数
                footerRow.getCell(2).setCellFormula(formulas[i]+"(C5:C"+(list.size() + 4) + ")" );
                //重量
                footerRow.getCell(3).setCellFormula(formulas[i]+"(D5:D"+(list.size() + 4) + ")" );
                //净重
                footerRow.getCell(4).setCellFormula(formulas[i]+"(E5:E"+(list.size() + 4) + ")" );
                //裁切宽度
                footerRow.getCell(5).setCellFormula(formulas[i]+"(F5:F"+(list.size() + 4) + ")" );
                //堆砌宽度
                footerRow.getCell(6).setCellFormula(formulas[i]+"(G5:G"+(list.size() + 4) + ")" );
            }

        }
        //合并
        sheet.addMergedRegion(new CellRangeAddress(list.size() + 4, list.size() + 7, 0, 0));
        sheet.addMergedRegion(new CellRangeAddress(list.size() + 4, list.size() + 7, 7, 8));

        sheet.getRow(list.size() + 4).getCell(11).setCellFormula("COUNTIF(I5:I" + (list.size() + 4) + ",\"=X\")" );
        sheet.getRow(list.size() + 5).getCell(11).setCellFormula("COUNTIF(J5:J" + (list.size() + 4) + ",\"=√\")" );
        sheet.getRow(list.size() + 6).getCell(11).setCellFormula("COUNTIF(K5:K" + (list.size() + 4) + ",\"=X\")" );
        sheet.getRow(list.size() + 7).getCell(11).setCellFormula("COUNTIF(H5:H" + (list.size() + 4) + ",\">0\")" );

    }

    private short getHeight(float height){
        return (short) (height * 20);
    }
    private short getWidth(float width){
        return (short) (width * 32.8);
    }

    private CellStyle getCellStyle(Workbook workbook, int fontSize ,XSSFColor titleColor){
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) fontSize);
        style.setFont(font);
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        if (titleColor == null){
            style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        } else {
            style.setFillForegroundColor(titleColor);
        }
        style.setBorderBottom(BorderStyle.MEDIUM);
        style.setBorderLeft(BorderStyle.MEDIUM);
        style.setBorderRight(BorderStyle.MEDIUM);
        style.setBorderTop(BorderStyle.MEDIUM);
        return style;
    }
}
